<template>
  <div class="step-panel">
    <h2>{{ stepTitle }}</h2>
    
    <!-- 申请状态显示 -->
    <div class="approval-status-section">
      <div class="status-card">
        <div class="status-header">
          <h3>申请状态</h3>
          <div class="status-badge" :class="getStatusClass(approvalStatus)">
            {{ getStatusText(approvalStatus) }}
          </div>
        </div>
        <div class="status-details">
          <div class="detail-row">
            <span class="detail-label">申请人：</span>
            <span class="detail-value">{{ currentUser.name }}</span>
            <span class="detail-role">({{ currentUser.role }})</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">申请时间：</span>
            <span class="detail-value">{{ formatTime(applicationTime) }}</span>
          </div>
          <div v-if="approvalStatus === 'approved'" class="detail-row">
            <span class="detail-label">审批人：</span>
            <span class="detail-value">{{ approverInfo.name }}</span>
            <span class="detail-role">({{ approverInfo.role }})</span>
          </div>
          <div v-if="approvalStatus === 'approved'" class="detail-row">
            <span class="detail-label">审批时间：</span>
            <span class="detail-value">{{ formatTime(approvalTime) }}</span>
          </div>
          <div v-if="approvalStatus === 'rejected'" class="detail-row">
            <span class="detail-label">拒绝原因：</span>
            <span class="detail-value reject-reason">{{ rejectReason }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <div class="loading-spinner"></div>
      <p>正在加载评估数据...</p>
    </div>

    <!-- 审批人视图：显示详细信息 -->
    <div v-else-if="isApproverView" class="review-content">
      
      <!-- 老人基本信息 -->
      <div class="review-section">
        <h3>一、老人基本信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <label>姓名：</label>
            <span>{{ localFormData.elder.name || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>身份证号：</label>
            <span>{{ localFormData.elder.idCard || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>性别：</label>
            <span>{{ localFormData.elder.gender || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>年龄：</label>
            <span>{{ localFormData.elder.age || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>联系电话：</label>
            <span>{{ localFormData.elder.contact || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>家庭住址：</label>
            <span>{{ localFormData.elder.address || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>民族：</label>
            <span>{{ getDictLabel(ethnicity, localFormData.elder.ethnicity) || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>政治面貌：</label>
            <span>{{ getDictLabel(political_status, localFormData.elder.politicalStatus) || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>婚姻状况：</label>
            <span>{{ getDictLabel(marital_status, localFormData.elder.maritalStatus) || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>文化程度：</label>
            <span>{{ getDictLabel(educational_level, localFormData.elder.education) || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>收入来源：</label>
            <span>{{ localFormData.elder.incomeSource || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>兴趣爱好：</label>
            <span>{{ localFormData.elder.hobby || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>医疗保险：</label>
            <span>{{ localFormData.elder.medicalInsurance || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label>医保卡号：</label>
            <span>{{ localFormData.elder.medicalCardNo || '未填写' }}</span>
          </div>
        </div>
      </div>

      <!-- 家属信息 -->
      <div class="review-section">
        <h3>二、家属信息</h3>
        <div class="family-members-review">
          <div
            v-for="(member, index) in localFormData.familyMembers"
            :key="index"
            class="family-member-review"
          >
            <div class="member-header">
              <span class="member-index">家属 {{ index + 1 }}</span>
              <span
                v-if="member.isEmergency === '是'"
                class="emergency-tag"
              >紧急联系人</span>
            </div>
            <div class="member-details">
              <div class="detail-item">
                <label>姓名：</label>
                <span>{{ member.name || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <label>联系电话：</label>
                <span>{{ member.contact || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <label>与老人关系：</label>
                <span>{{ getDictLabel(relationship_with_the_elderly, member.relationship) || '未填写' }}</span>
              </div>
            </div>
          </div>
          <div v-if="!localFormData.familyMembers || localFormData.familyMembers.length === 0" class="no-data">
            无家属信息
          </div>
        </div>
      </div>

      <!-- 健康状况 -->
      <div class="review-section">
        <h3>三、健康状况评估</h3>
        
        <!-- 疾病诊断 -->
        <div class="health-subsection">
          <h4>1. 疾病诊断</h4>
          <div class="disease-list">
            <span
              v-for="(disease, index) in localFormData.healthAssessment.diseaseDiagnosis"
              :key="index"
              class="disease-tag"
            >
              {{ disease }}
              <span
                v-if="disease === '其他' && localFormData.healthAssessment.otherDisease"
                class="other-detail"
              >({{ localFormData.healthAssessment.otherDisease }})</span>
            </span>
            <span
              v-if="!localFormData.healthAssessment.diseaseDiagnosis || localFormData.healthAssessment.diseaseDiagnosis.length === 0"
              class="no-data"
            >无疾病记录</span>
          </div>
        </div>

        <!-- 用药情况 -->
        <div class="health-subsection">
          <h4>2. 用药情况</h4>
          <div class="medicine-list">
            <div
              v-for="(medicine, index) in localFormData.healthAssessment.medicationInfo"
              :key="index"
              class="medicine-item-review"
            >
              <div class="medicine-header">
                <span class="medicine-name">{{ medicine.name || '未填写药物名称' }}</span>
              </div>
              <div class="medicine-details">
                <span v-if="medicine.method">服药方法：{{ medicine.method }}</span>
                <span v-if="medicine.dosage">用药剂量：{{ medicine.dosage }}</span>
                <span v-if="medicine.frequency">用药频率：{{ medicine.frequency }}</span>
              </div>
            </div>
            <div
              v-if="!localFormData.healthAssessment.medicationInfo || localFormData.healthAssessment.medicationInfo.length === 0"
              class="no-data"
            >无用药记录</div>
          </div>
        </div>

        <!-- 风险因素 -->
        <div class="health-subsection">
          <h4>3. 风险因素</h4>
          <div class="risk-events-review">
            <div
              v-for="(event, index) in riskEvents"
              :key="index"
              class="risk-event-review"
            >
              <span class="event-name">{{ event.name }}：</span>
              <span class="event-count">
                {{ getRiskEventCount(event.name) }}次
              </span>
            </div>
          </div>
        </div>

        <!-- 身体健康情况 -->
        <div class="health-subsection">
          <h4>4. 身体健康情况</h4>
          <div class="health-conditions-review">
            <!-- 伤口情况 -->
            <div class="health-condition-review">
              <div class="condition-name">伤口情况：</div>
              <div class="condition-options">
                <span
                  v-for="(option, optIndex) in localFormData.healthAssessment.woundCondition"
                  :key="optIndex"
                  class="condition-tag"
                >
                  {{ option }}
                </span>
                <span
                  v-if="!localFormData.healthAssessment.woundCondition || localFormData.healthAssessment.woundCondition.length === 0"
                  class="no-data"
                >无记录</span>
              </div>
            </div>
            
            <!-- 特殊医疗照护情况 -->
            <div class="health-condition-review">
              <div class="condition-name">特殊医疗照护情况：</div>
              <div class="condition-options">
                <span
                  v-for="(option, optIndex) in localFormData.healthAssessment.specialMedicalCare"
                  :key="optIndex"
                  class="condition-tag"
                >
                  {{ option }}
                </span>
                <span
                  v-if="!localFormData.healthAssessment.specialMedicalCare || localFormData.healthAssessment.specialMedicalCare.length === 0"
                  class="no-data"
                >无记录</span>
              </div>
            </div>
            
            <!-- 自理能力 -->
            <div class="health-condition-review">
              <div class="condition-name">自理能力：</div>
              <div class="condition-options">
                <span
                  v-for="(option, optIndex) in localFormData.healthAssessment.selfCareAbility"
                  :key="optIndex"
                  class="condition-tag"
                >
                  {{ option }}
                </span>
                <span
                  v-if="!localFormData.healthAssessment.selfCareAbility || localFormData.healthAssessment.selfCareAbility.length === 0"
                  class="no-data"
                >无记录</span>
              </div>
            </div>
            
            <!-- 痴呆前兆 -->
            <div class="health-condition-review">
              <div class="condition-name">痴呆前兆：</div>
              <div class="condition-options">
                <span
                  v-for="(option, optIndex) in localFormData.healthAssessment.dementiaPrecursors"
                  :key="optIndex"
                  class="condition-tag"
                >
                  {{ option }}
                </span>
                <span
                  v-if="!localFormData.healthAssessment.dementiaPrecursors || localFormData.healthAssessment.dementiaPrecursors.length === 0"
                  class="no-data"
                >无记录</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他情况说明 -->
        <div
          v-if="localFormData.healthAssessment.otherConditions"
          class="health-subsection"
        >
          <h4>5. 其他情况说明</h4>
          <div class="other-conditions">
            {{ localFormData.healthAssessment.otherConditions }}
          </div>
        </div>
      </div>

      <!-- 能力评估结果 -->
      <div class="review-section">
        <h3>四、能力评估结果</h3>
        <div class="ability-assessment-review">
          <!-- 自理能力评估 -->
          <div class="ability-category" v-if="localFormData.abilityAssessment.selfCareAbility && localFormData.abilityAssessment.selfCareAbility.length > 0">
            <h4>自理能力评估</h4>
            <div class="ability-scores">
              <div
                v-for="(item, index) in localFormData.abilityAssessment.selfCareAbility"
                :key="index"
                class="ability-score-item"
              >
                <span class="question-title">{{ item.question || `项目${index + 1}` }}：</span>
                <span class="question-score">
                  {{ item.score || 0 }}分
                </span>
              </div>
            </div>
          </div>

          <!-- 精神状态评估 -->
          <div class="ability-category" v-if="localFormData.abilityAssessment.mentalStatus && localFormData.abilityAssessment.mentalStatus.length > 0">
            <h4>精神状态评估</h4>
            <div class="ability-scores">
              <div
                v-for="(item, index) in localFormData.abilityAssessment.mentalStatus"
                :key="index"
                class="ability-score-item"
              >
                <span class="question-title">{{ item.question || `项目${index + 1}` }}：</span>
                <span class="question-score">
                  {{ item.score || 0 }}分
                </span>
              </div>
            </div>
          </div>

          <!-- 感知觉与社会参与 -->
          <div class="ability-category" v-if="localFormData.abilityAssessment.perceptionSocial && localFormData.abilityAssessment.perceptionSocial.length > 0">
            <h4>感知觉与社会参与</h4>
            <div class="ability-scores">
              <div
                v-for="(item, index) in localFormData.abilityAssessment.perceptionSocial"
                :key="index"
                class="ability-score-item"
              >
                <span class="question-title">{{ item.question || `项目${index + 1}` }}：</span>
                <span class="question-score">
                  {{ item.score || 0 }}分
                </span>
              </div>
            </div>
          </div>
          
          <!-- 兼容旧结构 -->
          <div class="ability-category" v-if="localFormData.abilityAssessment.answers && localFormData.abilityAssessment.answers.length > 0">
            <h4>能力评估得分</h4>
            <div class="ability-scores">
              <div
                v-for="(score, index) in localFormData.abilityAssessment.answers"
                :key="index"
                class="ability-score-item"
              >
                <span class="question-title">{{ abilityQuestions[index]?.title || `项目${index + 1}` }}：</span>
                <span class="question-score">
                  {{ score || 0 }}分
                </span>
              </div>
            </div>
          </div>
          
          <!-- 总分和等级 -->
          <div class="ability-summary">
            <div class="total-score-review">
              <strong>总分：{{ localFormData.assessmentReport.estimatedTotalScore || 0 }}分</strong>
            </div>
            <div class="ability-level">
              <span class="level-label">能力等级：</span>
              <span class="level-value" :class="getLevelClass(localFormData.assessmentReport.estimatedTotalScore || 0)">
                {{ localFormData.assessmentReport.finalLevel || '未评定' }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 评估报告摘要 -->
      <div class="review-section">
        <h3>五、评估报告摘要</h3>
        <div class="report-summary-review">
          <div class="summary-item">
            <label>能力最终等级：</label>
            <span class="final-level">{{ localFormData.assessmentReport.finalLevel || '未评定' }}</span>
          </div>
          <div
            v-if="localFormData.assessmentReport.changeBasis && localFormData.assessmentReport.changeBasis.length > 0"
            class="summary-item"
          >
            <label>等级变更依据：</label>
            <div class="change-basis-list">
              <span
                v-for="(basis, index) in localFormData.assessmentReport.changeBasis"
                :key="index"
                class="basis-tag"
              >
                {{ basis }}
                <span
                  v-if="basis === '其他' && localFormData.assessmentReport.otherBasis"
                  class="other-detail"
                >({{ localFormData.assessmentReport.otherBasis }})</span>
              </span>
            </div>
          </div>
          <div
            v-if="localFormData.assessmentReport.selfCareScore"
            class="summary-item"
          >
            <label>自理能力得分：</label>
            <span>{{ localFormData.assessmentReport.selfCareScore }}分</span>
          </div>
          <div
            v-if="localFormData.assessmentReport.mentalStatusScore"
            class="summary-item"
          >
            <label>精神状态得分：</label>
            <span>{{ localFormData.assessmentReport.mentalStatusScore }}分</span>
          </div>
          <div
            v-if="localFormData.assessmentReport.perceptionSocialScore"
            class="summary-item"
          >
            <label>感知与社会参与得分：</label>
            <span>{{ localFormData.assessmentReport.perceptionSocialScore }}分</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 申请人视图：只显示状态 -->
    <div v-else-if="isApplicantView && !loading" class="applicant-view">
      <div class="applicant-message">
        <div class="message-icon">
          <span v-if="approvalStatus === 'pending'">⏳</span>
          <span v-else-if="approvalStatus === 'approved'">✅</span>
          <span v-else-if="approvalStatus === 'rejected'">❌</span>
        </div>
        <div class="message-content">
          <h4 v-if="approvalStatus === 'pending'">申请审核中</h4>
          <h4 v-else-if="approvalStatus === 'approved'">申请已通过</h4>
          <h4 v-else-if="approvalStatus === 'rejected'">申请未通过</h4>
          <p v-if="approvalStatus === 'pending'">
            您的入住申请已提交，正在等待审批人审核。请耐心等待...
          </p>
          <p v-else-if="approvalStatus === 'approved'">
            恭喜！您的入住申请已通过审批。下一步将进行入住配置。
          </p>
          <p v-else-if="approvalStatus === 'rejected'">
            很抱歉，您的入住申请未通过审批。原因：{{ rejectReason }}
          </p>
        </div>
      </div>
    </div>

    <!-- 审批操作按钮（仅审批人可见） -->
    <div v-if="isApproverView && approvalStatus === 'pending' && !loading" class="approval-actions">
      <button class="reject-btn" @click="handleReject">拒绝申请</button>
      <button class="approve-btn" @click="handleApprove">批准申请</button>
    </div>

    <!-- 拒绝原因对话框 -->
    <div v-if="showRejectDialog" class="dialog-overlay">
      <div class="reject-dialog">
        <h3>拒绝申请</h3>
        <div class="dialog-content">
          <label>请填写拒绝原因：</label>
          <textarea
            v-model="rejectReasonInput"
            placeholder="请输入拒绝申请的具体原因..."
            rows="4"
            maxlength="200"
          ></textarea>
          <div class="char-count">{{ rejectReasonInput.length }}/200</div>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="cancelReject">取消</button>
          <button class="confirm-reject-btn" @click="confirmReject" :disabled="!rejectReasonInput">
            确认拒绝
          </button>
        </div>
      </div>
    </div>

    <div class="step-actions">
      <button @click="$emit('prev')">上一步</button>
      <button 
        @click="completeStep" 
        :disabled="!isStepValid || loading || isApplicantView"
      >
        {{ getNextButtonText() }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router'

// 引入API
import { getHealthAssessment, listHealthAssessment } from "@/api/le/healthAssessment"
import { getAbilityAssessment, listAbilityAssessment } from "@/api/le/abilityAssessment"
import { getAssessmentReport, listAssessmentReport } from "@/api/le/assessmentReport"
import { getPendingTasks, updatePendingTasks } from "@/api/le/pendingTasks"
import { getElderlyByElderlyId } from "@/api/le/elderly"
import { listMember } from "@/api/le/member"
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance();
const route = useRoute();

const { 
    ethnicity, 
    political_status, 
    marital_status, 
    educational_level,
    relationship_with_the_elderly,
 } = proxy.useDict(
    "ethnicity", 
    "political_status", 
    "marital_status", 
    "educational_level", 
    "relationship_with_the_elderly",
);

const props = defineProps({
  formData: {
    type: Object,
    required: true
  },
  elderlyId: {
    type: [String, Number],
    default: null
  },
  // 新增：从ptList跳转时传递的pendingTaskId
  pendingTaskId: {
    type: [String, Number],
    default: null
  }
})

const emit = defineEmits(['next', 'prev', 'update:form-data'])

const stepTitle = '第三步：内容确认'

// 本地状态
const localFormData = reactive(JSON.parse(JSON.stringify(props.formData)))

// 数据加载状态
const loading = ref(false)

// 页面类型判断
const isFromPtList = computed(() => {
  return !!props.pendingTaskId || route.query.pendingTaskId
})

const isApproverView = computed(() => {
  return isFromPtList.value
})

const isApplicantView = computed(() => {
  return !isFromPtList.value
})

// 审批相关状态
const approvalStatus = ref('pending')
const currentUser = ref({
  name: '张三',
  role: '审批人'
})
const approverInfo = ref({
  name: '李四',
  role: '护理部主任'
})
const applicationTime = ref(new Date())
const approvalTime = ref(null)
const rejectReason = ref('')
const showRejectDialog = ref(false)
const rejectReasonInput = ref('')

// 待办任务数据
const pendingTaskData = ref(null)

// 评估选项配置
const riskEvents = [
  { name: "跌倒" },
  { name: "走失" },
  { name: "噎食" },
  { name: "自杀" },
  { name: "昏迷" },
]

const abilityQuestions = [
  {
    title: "自理能力评估",
  },
  {
    title: "精神状态评估",
  },
  {
    title: "感知与社会参与",
  },
]

// 计算属性
const isStepValid = computed(() => {
  if (isApplicantView.value) {
    return true
  } else {
    return approvalStatus.value !== 'pending'
  }
})

// 方法
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const getStatusClass = (status) => {
  const statusClasses = {
    pending: 'status-pending',
    approved: 'status-approved',
    rejected: 'status-rejected'
  }
  return statusClasses[status] || 'status-pending'
}

const getStatusText = (status) => {
  const statusTexts = {
    pending: '审核中',
    approved: '已通过',
    rejected: '未通过'
  }
  return statusTexts[status] || '未知状态'
}

const getDictLabel = (dict, value) => {
  if (!dict || value === null || value === undefined) return ''
  // 确保value是数字类型进行比较
  const numValue = Number(value)
  const item = dict.find(item => Number(item.value) === numValue)
  return item ? item.label : ''
}

const getLevelClass = (score) => {
  if (score >= 25) return 'level-good'
  if (score >= 15) return 'level-fair'
  if (score >= 5) return 'level-poor'
  return 'level-bad'
}

const getRiskEventCount = (eventName) => {
  if (!localFormData.healthAssessment.riskFactors) return 0
  const event = localFormData.healthAssessment.riskFactors.find(item => item.name === eventName)
  return event ? event.count : 0
}

// 加载数据库数据
const loadDatabaseData = async () => {
  try {
    loading.value = true
    
    if (isFromPtList.value) {
      // 从ptList跳转进来，需要查询数据库
      await loadDataFromPendingTask()
    } else {
      // 从processEntry跳转进来，使用表单数据
    }
  } catch (error) {
    console.error('加载数据库数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 从待办任务加载数据
const loadDataFromPendingTask = async () => {
  try {
    const pendingTaskId = props.pendingTaskId || route.query.pendingTaskId
    
    if (!pendingTaskId) {
      console.error('未找到待办任务ID')
      return
    }

    // 1. 获取待办任务详情
    const pendingTaskRes = await getPendingTasks(pendingTaskId)
    if (pendingTaskRes.code === 200) {
      pendingTaskData.value = pendingTaskRes.data
      
      // 更新用户信息
      currentUser.value = {
        name: pendingTaskRes.data.applicat || '未知申请人',
        role: '申请人'
      }
      
      // 更新申请时间
      applicationTime.value = pendingTaskRes.data.applicationTime
      
      // 获取老人ID
      const elderlyId = pendingTaskRes.data.extraField2
      if (elderlyId) {
        // 将老人ID保存到localFormData中，确保传递给下一步
        localFormData.elder.id = elderlyId
        await loadElderlyAssessmentData(elderlyId)
      }
    }
  } catch (error) {
    console.error('加载待办任务数据失败:', error)
  }
}

// 根据老人ID加载评估数据
const loadElderlyAssessmentData = async (elderlyId) => {
  try {
    // 并行查询老人信息、家属信息、健康评估、能力评估、评估报告数据
    const [elderlyRes, memberRes, healthRes, abilityRes, reportRes] = await Promise.all([
      getElderlyByElderlyId(elderlyId),
      listMember({ 
        elderlyId: elderlyId,
        pageNum: 1,
        pageSize: 100  // 使用若依标准分页参数
      }),
      listHealthAssessment({ elderlyId: elderlyId }),
      listAbilityAssessment({ elderlyId: elderlyId }),
      listAssessmentReport({ elderlyId: elderlyId })
    ])

    // 处理老人基本信息
    if (elderlyRes.code === 200 && elderlyRes.data) {
      const elderlyData = elderlyRes.data
      
      // 根据API响应字段映射老人信息
      localFormData.elder = {
        id: elderlyData.elderlyId || elderlyData.id,
        name: elderlyData.elderlyName || elderlyData.name || '',
        idCard: elderlyData.elderlyIdCard || elderlyData.idCard || '',
        gender: elderlyData.gender || '',
        birthDate: elderlyData.birthDate || '',
        age: elderlyData.age || '',
        contact: elderlyData.elderlyPhone || elderlyData.contact || '',
        address: elderlyData.address || '',
        ethnicity: elderlyData.ethnicity || '',
        politicalStatus: elderlyData.politicalStatus || '',
        religiousBelief: elderlyData.religiousBelief || '',
        maritalStatus: elderlyData.maritalStatus || '',
        education: elderlyData.education || '',
        incomeSource: elderlyData.incomeSource || '',
        hobby: elderlyData.hobby || '',
        medicalInsurance: elderlyData.medicalInsurance || '',
        medicalCardNo: elderlyData.medicalCardNo || '',
        isDeleted: elderlyData.isDeleted || '1'
      }
    } else {
      // 老人信息查询失败
    }

    // 处理家属信息 - 使用若依标准查询方法
    if (memberRes.code === 200 && memberRes.rows && memberRes.rows.length > 0) {
      localFormData.familyMembers = memberRes.rows.map(member => ({
        id: member.id,
        name: member.name || member.memberName || '',
        contact: member.contact || member.phone || member.memberPhone || '',
        relationship: member.relationship || '',
        isEmergency: member.isEmergency || '否'
      }))
    } else {
      localFormData.familyMembers = []
    }

    // 处理健康评估数据
    if (healthRes.code === 200 && healthRes.rows && healthRes.rows.length > 0) {
      const healthData = healthRes.rows[0]
      // 解析JSON字段
      if (healthData.diseaseDiagnosis) {
        const diseaseData = JSON.parse(healthData.diseaseDiagnosis)
        localFormData.healthAssessment.diseaseDiagnosis = diseaseData.diseases || []
        localFormData.healthAssessment.otherDisease = diseaseData.otherDisease || ''
        localFormData.healthAssessment.showOtherDisease = diseaseData.otherDisease ? true : false
      }
      
      if (healthData.medicationInfo) {
        localFormData.healthAssessment.medicationInfo = JSON.parse(healthData.medicationInfo)
      }
      
      if (healthData.riskFactors) {
        localFormData.healthAssessment.riskFactors = JSON.parse(healthData.riskFactors)
      }
      
      if (healthData.woundCondition) {
        const woundData = JSON.parse(healthData.woundCondition)
        localFormData.healthAssessment.woundCondition = woundData.conditions || []
        localFormData.healthAssessment.otherWound = woundData.other || ''
        localFormData.healthAssessment.showOtherWound = woundData.other ? true : false
      }
      
      if (healthData.specialMedicalCare) {
        const medicalCareData = JSON.parse(healthData.specialMedicalCare)
        localFormData.healthAssessment.specialMedicalCare = medicalCareData.conditions || []
        localFormData.healthAssessment.otherMedicalCare = medicalCareData.other || ''
        localFormData.healthAssessment.showOtherMedicalCare = medicalCareData.other ? true : false
      }
      
      if (healthData.selfCareAbility) {
        const selfCareData = JSON.parse(healthData.selfCareAbility)
        localFormData.healthAssessment.selfCareAbility = selfCareData.conditions || []
        localFormData.healthAssessment.otherSelfCare = selfCareData.other || ''
        localFormData.healthAssessment.showOtherSelfCare = selfCareData.other ? true : false
      }
      
      if (healthData.dementiaPrecursors) {
        const dementiaData = JSON.parse(healthData.dementiaPrecursors)
        localFormData.healthAssessment.dementiaPrecursors = dementiaData.conditions || []
        localFormData.healthAssessment.otherDementia = dementiaData.other || ''
        localFormData.healthAssessment.showOtherDementia = dementiaData.other ? true : false
      }
      
      if (healthData.otherConditions) {
        const otherData = JSON.parse(healthData.otherConditions)
        localFormData.healthAssessment.otherConditions = otherData.text || ''
      }
    }

    // 处理能力评估数据
    if (abilityRes.code === 200 && abilityRes.rows && abilityRes.rows.length > 0) {
      const abilityData = abilityRes.rows[0]
      
      if (abilityData.selfCareAbility) {
        const selfCareData = JSON.parse(abilityData.selfCareAbility)
        // 保持完整的对象结构，包含question和score
        localFormData.abilityAssessment.selfCareAbility = selfCareData
      }
      
      if (abilityData.mentalStatus) {
        const mentalData = JSON.parse(abilityData.mentalStatus)
        // 保持完整的对象结构，包含question和score
        localFormData.abilityAssessment.mentalStatus = mentalData
      }
      
      if (abilityData.perceptionSocialParticipation) {
        const perceptionData = JSON.parse(abilityData.perceptionSocialParticipation)
        // 保持完整的对象结构，包含question和score
        localFormData.abilityAssessment.perceptionSocial = perceptionData
      }
    }

    // 处理评估报告数据
    if (reportRes.code === 200 && reportRes.rows && reportRes.rows.length > 0) {
      const reportData = reportRes.rows[0]
      
      localFormData.assessmentReport.selfCareScore = reportData.selfCareScore || 0
      localFormData.assessmentReport.mentalStatusScore = reportData.mentalStatusScore || 0
      localFormData.assessmentReport.perceptionSocialScore = reportData.perceptionSocialScore || 0
      localFormData.assessmentReport.estimatedTotalScore = reportData.estimatedTotalScore || 0
      localFormData.assessmentReport.preliminaryAbilityLevel = reportData.preliminaryAbilityLevel || ''
      localFormData.assessmentReport.finalLevel = reportData.finalAbilityLevel || ''
      
      if (reportData.levelChangeBasis) {
        localFormData.assessmentReport.changeBasis = JSON.parse(reportData.levelChangeBasis)
      }
      
      if (reportData.otherBasis) {
        const otherBasisData = JSON.parse(reportData.otherBasis)
        localFormData.assessmentReport.showOtherBasis = otherBasisData.showOther || false
        localFormData.assessmentReport.otherBasis = otherBasisData.otherText || ''
      }
    }
  } catch (error) {
    console.error('加载老人评估数据失败:', error)
  }
}

// 审批操作
const handleApprove = async () => {
  try {
    approvalStatus.value = 'approved'
    approvalTime.value = new Date()
    
    // 如果是审批人视图且有待办任务ID，更新待办任务状态
    if (isApproverView.value && props.pendingTaskId) {
      await updatePendingTaskStatus(2) // 2表示审批通过
    }
    
    updateFormData()
    ElMessage.success('审批通过！')
  } catch (error) {
    console.error('审批操作失败:', error)
    ElMessage.error('审批操作失败，请重试')
  }
}

const handleReject = () => {
  showRejectDialog.value = true
  rejectReasonInput.value = ''
}

const cancelReject = () => {
  showRejectDialog.value = false
  rejectReasonInput.value = ''
}

const confirmReject = async () => {
  if (rejectReasonInput.value.trim()) {
    try {
      approvalStatus.value = 'rejected'
      rejectReason.value = rejectReasonInput.value
      approvalTime.value = new Date()
      
      // 如果是审批人视图且有待办任务ID，更新待办任务状态
      if (isApproverView.value && props.pendingTaskId) {
        await updatePendingTaskStatus(3) // 3表示审批拒绝
      }
      
      showRejectDialog.value = false
      updateFormData()
      ElMessage.success('已拒绝申请')
    } catch (error) {
      console.error('拒绝操作失败:', error)
      ElMessage.error('拒绝操作失败，请重试')
    }
  }
}

// 更新待办任务状态
const updatePendingTaskStatus = async (status) => {
  try {
    if (!props.pendingTaskId) {
      return
    }
    
    const updateData = {
      id: props.pendingTaskId,
      status: status,
      isHandle: status === 2 ? 1 : 0, // 审批通过时设置为1，其他情况为0
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
    }
    
    const response = await updatePendingTasks(updateData)
    
    if (response.code === 200) {
      // 更新成功
    } else {
      console.error('待办任务状态更新失败:', response)
      throw new Error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新待办任务状态失败:', error)
    throw error
  }
}

const getNextButtonText = () => {
  if (loading.value) return '加载中...'
  if (isApplicantView.value) {
    return '等待审批完成'
  }
  if (isApproverView.value && approvalStatus.value === 'pending') {
    return '等待审批完成'
  }
  return '下一步'
}

const completeStep = () => {
  // 申请人界面不能进行下一步跳转
  if (isApplicantView.value) {
    ElMessage.warning('申请人界面无法进行下一步操作，请等待审批完成')
    return
  }
  
  updateFormData()
  emit('next')
}

// 更新表单数据
const updateFormData = () => {
  emit('update:form-data', localFormData)
}

// 监听父组件数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, newData)
}, { deep: true })

// 监听老人ID变化
watch(() => props.elderlyId, (newId) => {
  if (newId) {
    loadDatabaseData()
  }
})

// 组件挂载时加载数据
onMounted(() => {
  loadDatabaseData()
})
</script>

<style scoped>
/* 原有的样式保持不变，只添加加载状态的样式 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-section p {
  color: #6b7280;
  font-size: 16px;
}

/* 能力评估分类样式 */
.ability-category {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.ability-category:last-child {
  border-bottom: none;
}

.ability-category h4 {
  color: #374151;
  margin-bottom: 12px;
  font-size: 16px;
}

/* 其他原有样式保持不变 */
.step-panel h2 {
  color: #1f2937;
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.approval-status-section {
  margin-bottom: 30px;
}

.status-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  background: #f9fafb;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.status-header h3 {
  margin: 0;
  color: #1f2937;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.status-pending {
  background: #fef3c7;
  color: #d97706;
}

.status-approved {
  background: #d1fae5;
  color: #065f46;
}

.status-rejected {
  background: #fee2e2;
  color: #dc2626;
}

.status-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-label {
  color: #6b7280;
  font-weight: 500;
}

.detail-value {
  color: #1f2937;
}

.detail-role {
  color: #9ca3af;
  font-size: 14px;
}

.reject-reason {
  color: #dc2626;
  font-weight: 500;
}

.review-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.review-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  background: white;
}

.review-section h3 {
  margin: 0 0 16px 0;
  color: #1f2937;
  border-bottom: 2px solid #3b82f6;
  padding-bottom: 8px;
}

.review-section h4 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
}

.info-item span {
  color: #1f2937;
  font-size: 15px;
}

.family-members-review {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.family-member-review {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 16px;
  background: #f9fafb;
}

.member-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.member-index {
  font-weight: 600;
  color: #374151;
}

.emergency-tag {
  background: #fee2e2;
  color: #dc2626;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.member-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  gap: 8px;
}

.detail-item label {
  color: #6b7280;
  font-weight: 500;
  min-width: 80px;
}

.detail-item span {
  color: #1f2937;
}

.health-subsection {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f3f4f6;
}

.health-subsection:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.disease-list,
.medicine-list,
.risk-events-review,
.health-conditions-review {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.disease-tag,
.condition-tag,
.basis-tag {
  background: #eff6ff;
  color: #1e40af;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  border: 1px solid #dbeafe;
}

.other-detail {
  color: #6b7280;
  font-style: italic;
}

.no-data {
  color: #9ca3af;
  font-style: italic;
}

.medicine-item-review {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 12px;
  background: #f8fafc;
  width: 100%;
}

.medicine-header {
  margin-bottom: 8px;
}

.medicine-name {
  font-weight: 600;
  color: #1e40af;
}

.medicine-details {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #6b7280;
}

.risk-event-review {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  min-width: 200px;
}

.event-name {
  color: #374151;
  font-weight: 500;
}

.event-count {
  color: #dc2626;
  font-weight: 600;
}

.health-condition-review {
  margin-bottom: 12px;
}

.condition-name {
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.condition-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.other-conditions {
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 12px;
  color: #374151;
  line-height: 1.5;
}

.ability-assessment-review {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
}

.ability-scores {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.ability-score-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #e5e7eb;
}

.question-title {
  color: #374151;
}

.question-score {
  color: #1e40af;
  font-weight: 600;
}

.ability-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 2px solid #e5e7eb;
}

.total-score-review {
  font-size: 18px;
  color: #1f2937;
}

.ability-level {
  display: flex;
  align-items: center;
  gap: 8px;
}

.level-label {
  color: #6b7280;
}

.level-value {
  padding: 4px 12px;
  border-radius: 16px;
  font-weight: 600;
  font-size: 14px;
}

.level-good {
  background: #d1fae5;
  color: #065f46;
}

.level-fair {
  background: #fef3c7;
  color: #d97706;
}

.level-poor {
  background: #fed7aa;
  color: #ea580c;
}

.level-bad {
  background: #fecaca;
  color: #dc2626;
}

.report-summary-review {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.summary-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.summary-item label {
  color: #374151;
  font-weight: 500;
  min-width: 120px;
}

.final-level {
  background: #3b82f6;
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-weight: 600;
}

.change-basis-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.applicant-view {
  text-align: center;
  padding: 40px 20px;
}

.applicant-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  max-width: 400px;
  margin: 0 auto;
}

.message-icon {
  font-size: 48px;
}

.message-content h4 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 20px;
}

.message-content p {
  margin: 0;
  color: #6b7280;
  line-height: 1.5;
}

.approval-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin: 24px 0;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.reject-btn {
  background: #fef2f2;
  color: #dc2626;
  border: 1px solid #fecaca;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.reject-btn:hover {
  background: #fee2e2;
}

.approve-btn {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.approve-btn:hover {
  background: #a7f3d0;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.reject-dialog {
  background: white;
  border-radius: 8px;
  padding: 24px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

.dialog-content {
  margin-bottom: 20px;
}

.dialog-content label {
  display: block;
  margin-bottom: 8px;
  color: #374151;
  font-weight: 500;
}

.dialog-content textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  resize: vertical;
  font-family: inherit;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-reject-btn {
  background: #dc2626;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-reject-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 40px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

button:nth-of-type(1) {
  background-color: #f3f4f6;
  color: #1f2937;
}

button:nth-of-type(2),
button:last-child {
  background-color: #3b82f6;
  color: white;
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .member-details {
    grid-template-columns: 1fr;
  }
  
  .ability-summary {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .approval-actions {
    flex-direction: column;
  }
  
  .summary-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .status-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
